'use client';

import React, { useState, useEffect } from 'react';
import { Space, Table, Tag, Input, Button, Image, Modal, Form, InputNumber, Upload, Select, message } from 'antd';
import type { TableProps } from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import type { GetProp, UploadFile, UploadProps } from 'antd';

interface DataType {
  id: string;
  key: string;
  name: string;
  price: number;
  image: string;
  tags: string[];
  code: number;
}

const DishManagement: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [form] = Form.useForm();
  const [dishes, setDishes] = useState<DataType[]>([]);
  const [searchText, setSearchText] = useState('');
  const [currentRecord, setCurrentRecord] = useState<DataType | null>(null);

  useEffect(() => {
    fetchDishes();
  }, []);

  const fetchDishes = () => {
    fetch('/api/dishes')
      .then(res => res.json())
      .then(data => {
        if (Array.isArray(data)) {
          
          setDishes(data);
        } else {
          setDishes([]);
          console.error('Invalid data format:', data);
        }
      })
      .catch(error => {
        console.error('Failed to fetch dishes:', error);
        setDishes([]);
      });
  };

  // 图片处理相关函数
  type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

  const getBase64 = (file: FileType): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });

  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const handleChange: UploadProps['onChange'] = ({ file, fileList }) => {
    if (file.status === 'error') {
      message.error(file.response?.error || '上传失败');
      return;
    }
    
    const updatedFileList = fileList.map(f => {
      if (f.response) {
        f.url = f.response.url;
      }
      return f;
    });
    setFileList(updatedFileList);
  };

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  // 模态框相关函数
  const showModal = () => {
    setCurrentRecord(null);
    form.resetFields();
    setFileList([]);
    setIsModalOpen(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      
      const file = fileList[0];
      const imageUrl = file?.url || file?.response?.url || file?.response;
      if (!imageUrl) {
        throw new Error('请上传菜品图片');
      }

      const postData = {
        name: values.name,
        price: parseFloat(values.price),
        image: imageUrl,
        tags: values.tags || [],
      };

      // 根据是否有 currentRecord 来判断是编辑还是添加
      const url = currentRecord 
        ? `/api/dishes/${currentRecord.id}`
        : '/api/dishes';
      
      const method = currentRecord ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(postData),
      });
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || `${currentRecord ? '更新' : '添加'}菜品失败`);
      }

      const result = await response.json();
      fetchDishes();
      setIsModalOpen(false);
      form.resetFields();
      setFileList([]);
      setCurrentRecord(null);
      message.success(currentRecord ? '更新成功' : '添加成功');
    } catch (error:any) {
      console.error('Failed to save dish:', error);
      message.error(error.message || '保存失败');
    }
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
    setFileList([]);
    setCurrentRecord(null);
  };

  const handleEdit = (record: DataType) => {
    setCurrentRecord(record);
    form.setFieldsValue({
      name: record.name,
      price: record.price,
      tags: record.tags,
    });
    setFileList([{ 
      uid: record.id, 
      name: 'image.png', 
      status: 'done', 
      url: record.image 
    }]);
    setIsModalOpen(true);
  };

  const handleDelete = async (id: string) => {
    try {
      // 添加确认对话框
      const confirmed = await new Promise(resolve => {
        Modal.confirm({
          title: '确认删除',
          content: '确定要删除这个菜品吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => resolve(true),
          onCancel: () => resolve(false),
        });
      });

      if (!confirmed) return;

      const response = await fetch(`/api/dishes/${id}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || '删除失败');
      }

      message.success('删除成功');
      fetchDishes(); // 重新获取数据
    } catch (error) {
      console.error('Failed to delete dish:', error);
      message.error(error instanceof Error ? error.message : '删除失败');
    }
  };

  const handleSearch = () => {
    // 这里可以调用后端搜索 API，或者在前端过滤
    const filteredDishes = dishes.filter(dish => 
      dish.name.toLowerCase().includes(searchText.toLowerCase())
    );
    setDishes(filteredDishes);
  };

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: 80,
    },
    {
      title: '菜品图片',
      dataIndex: 'image',
      key: 'image',
      render: (image) => (
        <Image
          width={50}
          src={image}
        />
      ),
    },
    {
      title: '菜品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price.toFixed(2)}`,
    },
    {
      title: '标签',
      key: 'tags',
      dataIndex: 'tags',
      render: (tags) => (
        <>
          {tags.map((tag:any) => (
            <Tag color="success" key={tag}>
              {tag}
            </Tag>
          ))}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <a onClick={() => handleDelete(record.id)}>删除</a>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      <div style={{ marginBottom: '20px' }}>
        <Input 
          placeholder="请输入菜品名称" 
          style={{ width: '200px' }} 
          value={searchText}
          onChange={e => setSearchText(e.target.value)}
          onPressEnter={handleSearch}
        />
        <Button 
          type="primary" 
          style={{ marginLeft: '10px' }} 
          icon={<SearchOutlined />}
          onClick={handleSearch}
        >
          搜索
        </Button>
        <Button 
          type="primary" 
          style={{ marginLeft: '10px' }} 
          onClick={showModal}
        >
          添加菜品
        </Button>
      </div>

      <Table columns={columns} dataSource={dishes} rowKey="id" />

      <Modal
        title={currentRecord ? "编辑菜品" : "添加菜品"}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form form={form} layout="vertical">
          <Form.Item 
            label="菜品名称" 
            name="name"
            rules={[{ required: true, message: '请输入菜品名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item 
            label="菜品价格" 
            name="price"
            rules={[{ required: true, message: '请输入菜品价格' }]}
          >
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item 
            label="菜品图片" 
            name="image"
            rules={[{ required: true, message: '请上传菜品图片' }]}
          >
            <Upload
              action="/api/upload"  // 使用我们自己的上传接口
              listType="picture-card"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}
              name="file"
              accept="image/*"
              maxCount={1}
            >
              {fileList.length >= 1 ? null : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item 
            label="标签" 
            name="tags"
            rules={[{ required: true, message: '请选择标签' }]}
          >
            <Select mode="multiple" placeholder="请选择标签">
              <Select.Option value="主食">主食</Select.Option>
              <Select.Option value="荤菜">荤菜</Select.Option>
              <Select.Option value="素菜">素菜</Select.Option>
              <Select.Option value="甜食">甜食</Select.Option>
              <Select.Option value="水果">水果</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Image
        style={{ display: 'none' }}
        preview={{
          visible: previewOpen,
          onVisibleChange: (visible) => setPreviewOpen(visible),
          afterOpenChange: (visible) => !visible && setPreviewImage(''),
        }}
        src={previewImage}
      />
    </div>
  );
};

export default DishManagement;